﻿using Batman.Cache.Helpers;
using Batman.Cache.Providers;
using Castle.Core;
using Castle.Windsor;
using Microsoft.Extensions.DependencyInjection;

namespace Batman.Cache.Extensions
{
    public static class ServiceCollectionExtension
    {
        /// <summary>
        /// 内存缓存
        /// </summary>
        /// <param name="services"></param>
        public static void AddBatmanMemoryCache(this IServiceCollection services, IWindsorContainer container)
        {
            services.AddScoped<ICachingProvider, MemoryCachingProvider>();
            services.AddScoped<CacheInterceptor, CacheInterceptor>();
            services.AddScoped<CacheUsageHelper, CacheUsageHelper>();

            container.Kernel.ComponentRegistered += Kernel_ComponentRegistered; // 注册拦截器
        }

        private static void Kernel_ComponentRegistered(string key, Castle.MicroKernel.IHandler handler)
        {
            // 为实现IQueryCacheable接口的类添加缓存拦截器
            if (typeof(ICacheWorkable).IsAssignableFrom(handler.ComponentModel.Implementation))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(CacheInterceptor)));
            }
        }
    }
}
